package com.fast.controller.Async;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Future;


/**
 * Sync异步注解的用法
 */
@RestController
@RequestMapping("/sync")
@Slf4j
@EnableAsync
@Api(tags = "Sync异步注解")
public class SyncDemo {

    @Autowired
    private SyncService syncService;

    //1.需要在该类上加 @EnableAsync --写在启动类上 全项目都有
    //2.必须将方法写在service层加上 @Async --写在同方法不生效
    //3.不能对返回结果有任何操作，有操作就为同步了
    @GetMapping("/test")
    public String test() throws Exception {
        LocalDateTime start = LocalDateTime.now();
        //异步线程
        Future<String> result = syncService.newThread(start);
//        log.info("调用异步线程结果:" + result.get());//注释掉就是异步,放开是同步
        LocalDateTime end = LocalDateTime.now();
        log.info("主线程执行时间为" + Duration.between(start, end).toMillis());
        return "success";
    }

    /**
     * 响应时间：15毫秒
     * 线程1和线程2无序执行
     */
    @GetMapping("/singleThread")
    public String singleThread() {
        LocalDateTime start = LocalDateTime.now();
        new Thread(() -> {
            try {
                Thread.sleep(2000);
                System.out.println("线程1执行");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                Thread.sleep(2000);
                System.out.println("线程2执行");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        LocalDateTime end = LocalDateTime.now();
        log.info("主线程执行时间为" + Duration.between(start, end).toMillis());
        return "已提交";
    }


}
